//
//  myMapViewController.m
//  myMap
//
//  Created by Neelam Roy on 8/6/10.
//  Copyright __MyCompanyName__ 2010. All rights reserved.
//

#define allTrim(object)[object stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]

#import "myMapViewController.h"
#import "WebFectcher.h"
@implementation myMapViewController


@synthesize myMapView;
@synthesize problemTextView;
@synthesize address;
@synthesize contactNo;
@synthesize provincePickerView;
@synthesize cityPickerView,typePickerView;
@synthesize areaPickerView;
@synthesize province;
@synthesize  city;
@synthesize area,type;
double LongValue;
double LatValue;
BOOL isContactNo=NO;
NSMutableDictionary *dataDict;

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self ShowHideControlls];
    
    arrayTypes = [[NSMutableArray alloc] init];
    [arrayTypes addObject:@"sanitation"];
    [arrayTypes addObject:@"staff"];
    
    arrayProvinces = [[NSMutableArray alloc] init];
    [arrayProvinces addObject:@"punjab"];
    [arrayProvinces addObject:@"sindh"];
   // [arrayProvinces addObject:@"Balochistan"];
    //[arrayProvinces addObject:@"NWFP"];
   
    arrayCities = [[NSMutableArray alloc] init];
    [arrayCities addObject:@"lahore"];
    [arrayCities addObject:@"faisalabad"];
   // [arrayCities addObject:@"Faisalabad"];
    //[arrayCities addObject:@"Sargodhah"];
    //[arrayCities addObject:@"Lahore"];
   /* [arrayCities addObject:@"Okara"];
    [arrayCities addObject:@"Gujranwala"];
    [arrayCities addObject:@"Sialkot"];
    [arrayCities addObject:@"Karachi"];
    [arrayCities addObject:@"HyderAbad"];
    [arrayCities addObject:@"Sakhar"];
    [arrayCities addObject:@"Daddoo"];*/
   
    
    arrayAreas = [[NSMutableArray alloc] init];
    [arrayAreas addObject:@"model town"];
    [arrayAreas addObject:@"gulberg"];
   /* [arrayAreas addObject:@"Area3"];
    [arrayAreas addObject:@"Area4"];
    [arrayAreas addObject:@"Area5"];
    [arrayAreas addObject:@"Area6"];
    [arrayAreas addObject:@"Area7"];
    [arrayAreas addObject:@"Area8"];
    [arrayAreas addObject:@"Area9"];
    [arrayAreas addObject:@"Area10"];*/
    
    webFtch = [[WebFectcher alloc] init];
    webFtch.delegate = self;
    
    myMapView = [[MKMapView alloc] initWithFrame:CGRectMake(8,257 , 303, 177)];  
    myMapView.delegate=self;  
	
    [self.view addSubview:myMapView]; 
  //  [self.view  sendSubviewToBack:myMapView];
    [NSThread detachNewThreadSelector:@selector(displayMYMap) toTarget:self withObject:nil]; 

    [self createDataBase];
    problemTextView.delegate=self;
    address.delegate=self;
    contactNo.delegate=self;
    
    
	// add observer for the respective notifications (depending on the os version)
	if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.2) {
		[[NSNotificationCenter defaultCenter] addObserver:self 
												 selector:@selector(keyboardDidShow:) 
													 name:UIKeyboardDidShowNotification 
												   object:nil];		
	} else {
		[[NSNotificationCenter defaultCenter] addObserver:self 
												 selector:@selector(keyboardWillShow:) 
													 name:UIKeyboardWillShowNotification 
												   object:nil];
	}

}

-(void) ShowHideControlls
{
    [provincePickerView setHidden:YES];
    [cityPickerView setHidden:YES];
    [areaPickerView setHidden:YES];
    [typePickerView setHidden:YES];
    
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)thePickerView {
    
    return 1;
}

//PickerViewController.m
- (NSInteger)pickerView:(UIPickerView *)thePickerView numberOfRowsInComponent:(NSInteger)component {
    if(thePickerView.tag==101)
    return [arrayProvinces count];
    else if(thePickerView.tag==102)
    return [arrayCities count]; 
    else if(thePickerView.tag==103)
        return [arrayAreas count]; 
    else if(thePickerView.tag==104)
        return [arrayTypes count]; 
    else 
            return 0;
}

//PickerViewController.m
- (void)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    
    if(thePickerView.tag==101){
    /*if(row ==0)
    {
    // [arrayCities removeAllObjects];
    [arrayCities addObject:@"Lahore"];
    [arrayCities addObject:@"Okara"];
    [arrayCities addObject:@"Gujranwala"];
    [arrayCities addObject:@"Sialkot"];
    }
    else if(row==1)
    {
    //    [arrayCities removeAllObjects];
        [arrayCities addObject:@"Karachi"];
        [arrayCities addObject:@"HyderAbad"];
        [arrayCities addObject:@"Sakhar"];
        [arrayCities addObject:@"Daddoo"];
    }*/
        [thePickerView setHidden:YES];
        
        province.Text=[arrayProvinces objectAtIndex:row];
    }
    else if(thePickerView.tag==102){
        [thePickerView setHidden:YES];
        city.Text=[arrayCities objectAtIndex:row];

    }
    else if(thePickerView.tag==103){
        [thePickerView setHidden:YES];
        area.Text=[arrayAreas objectAtIndex:row];
        
    }
    else if(thePickerView.tag==104){
        [thePickerView setHidden:YES];
        type.Text=[arrayTypes objectAtIndex:row];
        
    }
    
   // NSLog(@"Selected Color: %@. Index of selected color: %i", [arrayProvinces objectAtIndex:row], row);
}

//PickerViewController.m
- (NSString *)pickerView:(UIPickerView *)thePickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    if(thePickerView.tag==101)
        return [arrayProvinces objectAtIndex:row];
    else if(thePickerView.tag==102)
     return [arrayCities objectAtIndex:row];
    else if(thePickerView.tag==103)
        return [arrayAreas objectAtIndex:row];
    else if(thePickerView.tag==104)
        return [arrayTypes objectAtIndex:row];
    else 
        return @"";
    
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    NSLog(@"OldLocation %f %f", oldLocation.coordinate.latitude, oldLocation.coordinate.longitude);
    NSLog(@"NewLocation %f %f", newLocation.coordinate.latitude, newLocation.coordinate.longitude);
}
-(void)displayMYMap
{

	MKCoordinateRegion region;  
    MKCoordinateSpan span;  
    span.latitudeDelta=0.2;  
    span.longitudeDelta=0.2;  
	
    CLLocationCoordinate2D location;  
   
	location.latitude = 31.4890453 ;
	location.longitude = 74.3223378;

	
		
    region.span=span;  
    region.center=location;  
	
    [myMapView setRegion:region animated:TRUE];  
    [myMapView regionThatFits:region];  
}

-(IBAction) backButtonAction
{
	[self dismissModalViewControllerAnimated:YES];
    //	[self autorelease];
    //[self findContact];
}


/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}

-(IBAction) provinceButtonAction
{
    [self ShowHideControlls];
    [provincePickerView setHidden:NO];
    [self.view  bringSubviewToFront:provincePickerView];
   
}
-(IBAction) cityButtonAction
{
    [self ShowHideControlls];
    [cityPickerView setHidden:NO];
     [self.view  bringSubviewToFront:cityPickerView];
}
-(IBAction) areaButtonAction
{
    [self ShowHideControlls];
    [areaPickerView setHidden:NO];
     [self.view  bringSubviewToFront:areaPickerView];
}
-(IBAction) typeButtonAction
{
    [self ShowHideControlls];
    [typePickerView setHidden:NO];
     [self.view  bringSubviewToFront:typePickerView];
    
}
-(IBAction) submitButtonAction;
{
    if([allTrim( problemTextView.text ) length] == 0 || [allTrim( address.text ) length]==0 || [allTrim( province.text ) length]==0 || [allTrim( city.text ) length]==0 || [allTrim( area.text ) length]==0){
       
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error Message:" message:@"Fill All the Mendatory fields"  delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
        [alert release];
        
    }
    else{
    dataDict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:nil];
    [dataDict setObject:problemTextView.text forKey:@"problem"];
    [dataDict setObject:address.text forKey:@"street"];
    [dataDict setObject:province.text  forKey:@"province"];
    [dataDict setObject:city.text forKey:@"city"];
    [dataDict setObject:area.text  forKey:@"area"];
    [dataDict setObject:contactNo.text  forKey:@"phone"];
    [dataDict setObject:type.text  forKey:@"type"];    
    
    [NSThread detachNewThreadSelector:@selector(callWebFetcherWithData:) toTarget:self withObject:dataDict]; 
    }
}

#pragma mark delegates
-(void) webFetcherSuccessWithData:(NSDictionary*)dict{
    [self removeActivityIndicator]; 
    if(dict!=nil){    
        if([[dict objectForKey:@"status"] isEqualToString:@"Success"]){
     
            [self performSelectorOnMainThread:@selector(saveData:) withObject:dict waitUntilDone:NO];

        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Your Complaint-ID is:" message:[dict objectForKey:@"complaint-ID"]  delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
        [alert release];
        }
        //  [self saveData:dict];
    }else{
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Please check your internet connection and retry."  delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
        [alert release];
    }
}

-(void) callWebFetcherWithData:(NSDictionary*)dict{
    
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
   [self performSelectorOnMainThread:@selector(drawActivityIndicator) withObject:nil waitUntilDone:YES];
    [dict retain];
    [webFtch callDataWithURL:@"http://securefy.com:8080/watsan/register_complaints.php" andData:dict];
    [dict release];
    [pool release];
}

-(void) drawActivityIndicator{
	if(actView == nil){
    //    screenRect = [[UIScreen mainScreen] bounds];
		UIActivityIndicatorView *actIndicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
		actView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
		actView.backgroundColor = [UIColor blackColor];
		actView.alpha = 0.8;
        actView.tag = 9;
		actIndicator.center=self.view.center;
		[actIndicator startAnimating];
		[actView addSubview:actIndicator];
		[actIndicator release];
		[self.view addSubview:actView];
		[actView release];
      //  tabBarCtr.tabBar.userInteractionEnabled = NO;
	}
	
}
-(void) removeActivityIndicator{
    
    if(actView){
		[actView removeFromSuperview];
		actView = nil;
      //  tabBarCtr.tabBar.userInteractionEnabled = YES;
	}else{
       // tabBarCtr.tabBar.userInteractionEnabled = YES;
    }
}


- (void) saveData:(NSDictionary*)dict
{
    sqlite3_stmt    *statement;
    
    const char *dbpath = [databasePath UTF8String];
    
    if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
    {
                
       NSString *insertSQL = [NSString stringWithFormat: @"INSERT INTO problems (problem, status, street,area,city,province,contact,date,traking_id,revisions,comments,type) VALUES (\"%@\", \"%@\", \"%@\", \"%@\", \"%@\", \"%@\", \"%@\", \"%@\", \"%@\", \"%i\", \"%@\", \"%@\")", [dataDict objectForKey:@"problem"],[dict objectForKey:@"status"],[dataDict objectForKey:@"street"],[dataDict objectForKey:@"area"],[dataDict objectForKey:@"city"],[dataDict objectForKey:@"province"],[dataDict objectForKey:@"phone"],[NSDate date],[dict objectForKey:@"complaint-ID"],1,@"", [dataDict objectForKey:@"type"] ];
        
        const char *insert_stmt = [insertSQL UTF8String];
        
        sqlite3_prepare_v2(contactDB, insert_stmt, -1, &statement, NULL);
        if (sqlite3_step(statement) == SQLITE_DONE)
        {
            NSLog( @"Contact added");
            } else {
            NSLog(@"Failed to add contact");
            NSLog(@"%s", sqlite3_errmsg(contactDB));
        }
        sqlite3_finalize(statement);
        sqlite3_close(contactDB);
    }

}

-(void) createDataBase
{ 
    NSString *docsDir;
    NSArray *dirPaths;
    
    // Get the documents directory
    dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    
    docsDir = [dirPaths objectAtIndex:0];
    
    // Build the path to the database file
    databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: @"contacts.db"]];
    
    NSFileManager *filemgr = [NSFileManager defaultManager];
    
    if ([filemgr fileExistsAtPath: databasePath ] == NO)
    {
		const char *dbpath = [databasePath UTF8String];
        
        if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
        {
            char *errMsg;
            const char *sql_stmt = "CREATE TABLE IF NOT EXISTS problems (ID INTEGER PRIMARY KEY AUTOINCREMENT, problem TEXT, status TEXT, street TEXT,area TEXT,city VARCHAR,province VARCHAR,contact VARCHAR, date DATETIME, traking_id VARCHAR, revisions INTEGER,comments  TEXT,type  TEXT)";
            
            
          /*  CREATE TABLE IF NOT EXISTS `problems` (
                                                   `id` int(11) NOT NULL AUTO_INCREMENT,
                                                   `problem` text NOT NULL,
                                                   `status` varchar(16) NOT NULL,
                                                   `street` text NOT NULL,
                                                   `area` varchar(24) NOT NULL,
                                                   `city` varchar(24) NOT NULL,
                                                   `province` varchar(24) NOT NULL,
                                                   `contact` varchar(16) NOT NULL,
                                                   `date` datetime NOT NULL,
                                                   `traking-id` varchar(24) NOT NULL,
                                                   `revisions` int(11) NOT NULL,
                                                   `comments` text NOT NULL,
                                                   PRIMARY KEY (`id`)
                                                   ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;*/
            
            if (sqlite3_exec(contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
            {
              //  status.text = @"Failed to create table";
            }
            
            sqlite3_close(contactDB);
            
        } else {
          //  status.text = @"Failed to open/create database";
        }
    }
    
    [filemgr release];

}



#pragma TextField Delegates
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
   // [self scrollToEnterText];
    if(textField.tag==2000)
        isContactNo=YES;
    else {
        isContactNo=NO;
    }
    [self ShowHideControlls];
    return YES;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
   // [self scrollBackToStart];
    return YES;
}
#pragma TextView Delegates
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    if([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
     //   [self scrollBackToStart];
        
        return NO;
    }
    return YES;
}
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView{
   // [self scrollToEnterText];
   // placeHolderlbl.hidden = YES;
    
    [self ShowHideControlls]; 
	return YES;
}



- (void)addButtonToKeyboard {
	// create custom button
	UIButton *doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
	doneButton.frame = CGRectMake(0, 163, 106, 53);
	doneButton.adjustsImageWhenHighlighted = NO;
	if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.0) {
		[doneButton setImage:[UIImage imageNamed:@"DoneUp3.png"] forState:UIControlStateNormal];
		[doneButton setImage:[UIImage imageNamed:@"DoneDown3.png"] forState:UIControlStateHighlighted];
	} else {        
		[doneButton setImage:[UIImage imageNamed:@"DoneUp.png"] forState:UIControlStateNormal];
		[doneButton setImage:[UIImage imageNamed:@"DoneDown.png"] forState:UIControlStateHighlighted];
	}
	[doneButton addTarget:self action:@selector(doneButton:) forControlEvents:UIControlEventTouchUpInside];
	// locate keyboard view
	UIWindow* tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];
	UIView* keyboard;
	for(int i=0; i<[tempWindow.subviews count]; i++) {
		keyboard = [tempWindow.subviews objectAtIndex:i];
		// keyboard found, add the button
		if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.2) {
			if([[keyboard description] hasPrefix:@"<UIPeripheralHost"] == YES)
				[keyboard addSubview:doneButton];
		} else {
			if([[keyboard description] hasPrefix:@"<UIKeyboard"] == YES)
				[keyboard addSubview:doneButton];
		}
	}
}

- (void)keyboardWillShow:(NSNotification *)note {
	// if clause is just an additional precaution, you could also dismiss it
	if ([[[UIDevice currentDevice] systemVersion] floatValue] < 3.2 && isContactNo) {
		[self addButtonToKeyboard];
	}
}

- (void)keyboardDidShow:(NSNotification *)note {
	// if clause is just an additional precaution, you could also dismiss it
	if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.2&& isContactNo) {
		[self addButtonToKeyboard];
    }
}


- (void)doneButton:(id)sender {
//	NSLog(@"doneButton");
   // NSLog(@"Input: %@", textField.text);
    [contactNo resignFirstResponder];
}


- (void)dealloc {
    [super dealloc];
    [[NSNotificationCenter defaultCenter] removeObserver:self];

	[myMapView release];
}

@end
